import axios from "axios"
import { Toast } from "vant"
import router from '../router/index'

axios.defaults.baseURL = 'http://47.99.134.126:7008/api'

//允许跨域 
axios.defaults.withCredentials = true;

axios.defaults.headers["X-Requested-With"] = "XMLHTTPRequest";
axios.defaults.headers.post["Content-Type"] = "application/json";

axios.interceptors.request.use(config => {
    // 获取token
  let token = window.localStorage.getItem('token');
  // 添加token
  token && (config.headers.Authorization = token);
    return config;
}, error => {
    // 对请求错误做些什么

    Message.error({ message: '请求超时!' })
    return Promise.error(error);
})

axios.interceptors.response.use(res => {
    console.log(res);

    if (typeof res.data !== "object") {
        Toast.fail("服务器异常");
        return Promise.reject(res)
    }
    if (res.data.code != 200) {
        if (res.data.msg) {
            Toast.fail(res.data.msg)
        }
        // 未登录的情况
        if (res.data.code == 401) {
            console.log(router);
            router.push({ path: "/login" })
        }
        return Promise.reject(res.data)
    }
    return res.data;
})

export default axios;